// index/pages/mzhSerch/mzhSerch.js
const https = require('../../../utils/https.js');

Page({
    data: {
        lisiContent: [],
        hotSearchList: [], // 热门搜索数据
        searchHistoryList: [], // 历史搜索数据
        url: '',
        value: '',
    },

    fanhui() {
        wx.switchTab({
            url: '/pages/index/index',
        })
    },

    // 用户搜索行为
    onSearch(e) {
        const keyword = e.detail;
        console.log('用户输入的搜索关键词为：', keyword);

        // ===== 上报搜索行为 =====
        https.POST('/search/searchhot/report', {
                keyword
            },
            (res) => {
                console.log('搜索上报成功:', res)
            },
            (err) => {
                console.error('搜索上报失败:', err)
            }
        );

        // 添加到本地缓存
        var history = this.data.searchHistoryList
        var t = true
        for (var i = 0; i < history.length; i++) {
            if (history[i] == keyword) {
                t = false
                break
            }
        }
        if (t) {
            history.push(keyword)
        }
        wx.setStorageSync('searchHistoryList', history)

        // 跳转到搜索结果
        wx.navigateTo({
            url: `/index/pages/mzhSerchResults/mzhSerchResults?keyword=${keyword}`,
        })
    },

    onLoad(options) {
        var url = options.url
        if (url != null && url != '') {
            this.setData({
                url
            })
            wx.switchTab({
                url: '/pages/index/index'
            })
        }
        // 加载热门搜索和历史
        this.loadHotSearchData();
        this.loadSearchHistory();
    },

    /**
     * 加载热门搜索数据（从 Redis）
     */
  loadHotSearchData() {
      https.GET('/search/searchhot/list', {},
          (res) => {
              if (res.code === 200 && res.rows) {
                  // 映射并排序
                  const list = res.rows.map(item => ({
                          id: item.id, // 保留唯一 id，避免 wx:for 渲染问题
                          keyword: item.keyword || '',
                          score: item.score || 0
                      }))
                      .sort((a, b) => b.score - a.score); // 按 score 降序排序

                  this.setData({
                      hotSearchList: list
                  });
              } else {
                  console.error('获取热门搜索失败:', res.msg);
              }
          },
          (err) => {
              console.error('请求热门搜索接口失败:', err);
              
          
          }
      );
  },



    clearSearch() {
        console.log("点击了清空用户搜索记录");
        wx.removeStorageSync('searchHistoryList')
        this.setData({
            searchHistoryList: []
        })
    },

    loadSearchHistory() {
        var history = wx.getStorageSync('searchHistoryList') || []
        this.setData({
            searchHistoryList: history
        })
    },

    // 点击搜索历史项
    onSearchHistoryTap(e) {
        const keyword = e.currentTarget.dataset.keyword;
        console.log('点击了搜索历史:', keyword);

      
        https.POST('/search/searchhot/click', {
                keyword
            },
            (res) => {
                console.log('历史搜索点击上报成功:', res)
            },
            (err) => {
                console.error('历史搜索点击上报失败:', err)
            }
        );
 
        wx.navigateTo({
            url: `/index/pages/mzhSerchResults/mzhSerchResults?keyword=${keyword}`
        });
    },

    // 点击热门搜索关键词
    // 点击热门搜索关键词
    onHotSearchTap(e) {
        const keyword = e.currentTarget.dataset.keyword;
        console.log('点击了热门搜索:', keyword);

        // ===== 上报点击行为 =====
        https.POST('/search/searchhot/click', {
                keyword
            },
            (res) => {
                console.log('点击热搜上报成功:', res)
            },
            (err) => {
                console.error('点击热搜上报失败:', err)
            }
        );

        // ===== 添加到搜索历史 =====
        let history = this.data.searchHistoryList;
        if (!history.includes(keyword)) {
            history.push(keyword);
            wx.setStorageSync('searchHistoryList', history);
            this.setData({
                searchHistoryList: history
            });
        }

        // 跳转到搜索结果页
        wx.navigateTo({
            url: `/index/pages/mzhSerchResults/mzhSerchResults?keyword=${keyword}`
        });
    },


    onShow() {
        this.loadHotSearchData();
        this.loadSearchHistory();
        this.setData({
            value: ''
        })
    },
})
